<template>
  <div>
    <button @click="addItem">添加项目</button>
    <button @click="removeItem" :disabled="items.length ==0">删除最后一项</button>

    <transition-group name="list" tag="ul">
      <li
        v-for="(item, index) in items"
        :key="item.id"
        :class="{'new-item': item.isNew, 'removed-item': item.isRemoved}"
      >
        {{ item.text }}
      </li>
    </transition-group>
  </div>
</template>

<script setup>
import { ref } from 'vue'

const items = ref([
  { id: 1, text: '项目1', isNew: false, isRemoved: false },
  { id: 2, text: '项目2', isNew: false, isRemoved: false }
])

const addItem = () => {
  const newItem = {
    id: Date.now(),
    text: `项目${items.value.length + 1}`,
    isNew: true,
    isRemoved: false
  }
  items.value.push(newItem)

  setTimeout(() => {
    newItem.isNew = false
  }, 1000) // 1秒后移除新增状态
}

const removeItem = () => {
  if (items.value.length > 0) {
    const lastItem = items.value[items.value.length - 1]
    lastItem.isRemoved = true

    setTimeout(() => {
      items.value = items.value.filter(item => !item.isRemoved)
    }, 1000) // 1秒后执行删除
  }
}
</script>

<style scoped>
/* 列表基础动画 */
.list-enter-active, .list-leave-active {
  transition: all 0.5s ease;
}
.list-enter-from {
  opacity: 0;
  transform: translateX(30px);
}
.list-leave-to {
  opacity: 0;
  transform: translateX(-30px);
}

/* 状态样式 */
.new-item {
  background-color: #d4edda !important; /* 绿色背景，表示新增 */
}

.removed-item {
  background-color: #f8d7da !important; /* 红色背景，表示删除 */
}

/* 可选：美化列表 */
ul {
  list-style: none;
  padding: 0;
  margin-top: 10px;
}

li {
  padding: 8px;
  margin-bottom: 4px;
  background-color: #f0f0f0;
  border-radius: 4px;
}
</style>